<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 编辑用户资料
 *
 * @author      Eden
 * @datetime    2016/12/1 00:03
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Edit_Model extends API_Model
{
    /**
     * 需要验证的字段
     * @var array
     */
    private $fields = array('userId', 'nickName', 'avatar', 'trueName');
    private $error = '';
    private $userId = '';

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {
            if ($this->input->method(true) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }
            $colParams = $this->_collectFields($params);
            if (empty($colParams)) {
                $send['error'] = '参数错误';
                break;
            }
            $this->userId = value($params, 'userId');
            $this->_checkParams($colParams);
            $res = $this->saveProfile($colParams);
            if (!$res) {
                $send['error'] = empty($this->error) ? '保存失败' : $this->error;
            } else {
                $send['state'] = true;
                $send['data'] = $this->_getUserInfo();
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 返回用户信息
     * @return mixed
     */
    private function _getUserInfo()
    {
        $db = clone($this->db);
        $q = $db->select('u.id as userId, u.nickName, up.trueName, u.phone, up.avatar, u.lastIp, u.lastTime, u.status')
            ->from('user as u')
            ->where('u.id', $this->userId)
            ->join('user_profile as up', 'up.userId = u.id')
            ->get();
        $row = $q->row_array();
        if (empty($row)) {
            $this->output->send(array('state' => false, 'error' => '用户不存在'));
        }
        $row['userId'] = intval($row['userId']);
        $row['status'] = intval($row['status']);
        return $row;
    }

    /**
     * 保存修改
     * @param $params
     * @return bool
     */
    private function saveProfile($params)
    {
        $userData = $profileData =  array();
        foreach ($params as $key => $value) {
            if (in_array($key, array('nickName'))) {
                $userData[$key] = $value;
            }
            if (in_array($key, array('avatar', 'trueName'))) {
                $profileData[$key] = $value;
            }
        }

        try {
            $this->db->trans_start();
            if (!empty($userData)) {
                $this->db->where('id', $this->userId);
                $this->db->update('user', $userData);
            }
            if (!empty($profileData)) {
                $this->db->where('userId', $this->userId);
                $this->db->update('user_profile', $profileData);
            }
            $this->db->trans_complete();

            if ($this->db->trans_status() === true) {
                return true;
            }
        } catch (PDOException $e) {
            $this->error = '修改失败';
            return false;
        }
        $this->error = '修改失败';
        return false;
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function _checkParams($params = array())
    {
        $send['state'] = false;
        do{

            if (empty($params['userId'])) {
                $send['error'] = '参数错误';
                break;
            }

            $p = array();
            unset($params['userId']);
            foreach ($params as $key => $param) {
                if ($key == 'nickName' && empty($param)) {
                    $send['error'] = '昵称错误';
                    break 2;
                }

                if ($key == 'avatar' && empty($param)) {
                    $send['error'] = '请重新上传头像';
                    break 2;
                }
                $p[$key] = $param;
            }

            if (empty($p)) {
               $send['error'] = '没有任何修改';
               break;
            }
            return true;
        } while(false);
        $this->output->send($send);
    }

    /**
     * 收集数据
     * @param array $params
     * @return array
     */
    public function _collectFields(Array $params)
    {
        $collects = array();
        foreach($params as $key => $value) {
            if (in_array($key, $this->fields)) {
                $collects[$key] = $value;
            }
        }
        return $collects;
    }
}
